Snake.prototype.init = function () {

    var snakeBody1 = SquareFactory.create('SnakeBody', 1, 1);
    var snakeBody2 = SquareFactory.create('SnakeBody', 2, 1);
    var snakeHead = SquareFactory.create('SnakeHead', 3, 1);

    snakeBody1.prev = null;
    snakeBody1.next = snakeBody2;
    snakeBody2.prev = snakeBody1;
    snakeBody2.next = snakeHead;
    snakeHead.prev = snakeBody2;
    snakeHead.next = null;

    snakeBody1.renderDom();
    snakeBody2.renderDom();
    snakeHead.renderDom();

    this.tail = snakeBody1;
    this.head = snakeHead;
}



Snake.moveRule = {
    "right": {
        x: 1,
        y: 0
    },
    "left": {
        x: -1,
        y: 0
    },
    "top": {
        x: 0,
        y: -1
    },
    "bottom": {
        x: 0,
        y: 1
    }
}

Snake.prototype.move = function () {
    // 下一个格子是什么
    // snakeHead.x y + direction
    var nextSquareInfo = this.getNextSquareStatus();
    var status = nextSquareInfo.status;
    if (this.hitSelf(nextSquareInfo)) {
        eventBus.emit("gameOver");
        return;
    }
    if (Snake.refl[status] === 'wall') {
        eventBus.emit("gameOver");
    } else if (Snake.refl[status] === 'floor') {
        this.walk(nextSquareInfo);
    } else if (Snake.refl[status] === 'food') {
        this.eatFood(nextSquareInfo);
    }
}
Snake.prototype.hitSelf = function ({ x, y }) {
    var cur = this.tail.next; // tail 
    while (cur) {
        if (cur.x === x && cur.y === y) {
            return true;
            break;
        }
        cur = cur.next;
    }
    return false;
}

Snake.prototype.walk = function ({ x, y }, isEatFood) {
    var newSnakeBody = SquareFactory.create("SnakeBody", this.head.x, this.head.y);
    this.head.x = x;
    this.head.y = y;
    this.head.updateDom();
    newSnakeBody.next = this.head;
    newSnakeBody.prev = this.head.prev;
    this.head.prev.next = newSnakeBody;
    this.head.prev = newSnakeBody;
    newSnakeBody.renderDom();


    if (!isEatFood) {
        this.tail.removeDom();
        this.tail = this.tail.next;
        this.tail.prev = null;
    }

}

Snake.prototype.eatFood = function ({ x, y }) {
    this.walk({ x, y }, true);
    eventBus.emit("eat", this);
}



Snake.prototype.getNextSquareStatus = function () {
    var x = this.head.x;
    var y = this.head.y;
    x += Snake.moveRule[this.direction].x;
    y += Snake.moveRule[this.direction].y;
    return {
        status: Snake.map[y][x],
        x,
        y
    }
}


Snake.refl = {
    0: "wall",
    1: 'floor',
    27: "food"
}